<template>
  <div class="selectors full">
    <selector v-model="currentTime" label="截止日期" :showAllOption="false" :columns="times" />
  </div>
  <Popup v-model:show="showPicker" position="buttom" style="width: 100%; left: 0; bottom: 0">
    <Picker :columns="times" :item-height="32" @cancel="showPicker = false" @confirm="changeTime" />
  </Popup>
  <div class="content" v-for="item of holders">
    <h3>{{ item.holder_name }}</h3>
    <div>
      <b>{{ helpers.friendlyNumbers(item.held_num) }}</b>
      <b>{{ item.held_ratio }}%</b>
      <b><component :is="getChangeText(item)" /></b>
    </div>
  </div>
</template>
<script setup>
  import { useRoute } from 'vue-router';
  import { ref, h, inject, reactive, watch, watchEffect, onMounted } from 'vue';
  import { Field, Popup, Picker } from 'vant';

  import helpers from '~/libs/helpers.js';

  const $route = useRoute();
  const $http = inject('$http');

  const times = ref([]);
  const holders = ref([]);
  const currentTime = ref('');
  const currentShare = ref('');
  const showPicker = ref(false);

  async function loadTopHolders() {
    let res = await $http.get(`/api/shares/${currentShare.value}/topholder`);

    times.value = (res.data.times || []).map(t => {
      return { text: t.name, value: t.value };
    });

    holders.value = res.data.items;
    currentTime.value = times.value[0].value;
  }

  watch(currentTime, async val => {
    showPicker.value = false;

    let res = await $http.get(`/api/shares/${currentShare.value}/topholder?start=${val}`);

    holders.value = res.data.items;
  });

  function getChangeText(record) {
    if (record.chg == 0) {
      return h('span', '不变');
    } else {
      return h(
        'span',
        {
          style: {
            color: (record.chg || 1) > 0 ? '#ed4014' : '#19be6b'
          }
        },
        record.chg == null ? '新进股东' : record.chg + '%'
      );
    }
  }

  onMounted(() => {
    currentShare.value = $route.params.code;

    loadTopHolders();
  });

  watchEffect(() => {
    currentShare.value = $route.params.code;

    loadTopHolders();
  });
</script>
<style lang="less" scoped>
  .content {
    user-select: none;
    background: #fff;
    padding: 10px 10px 5px 10px;
    border-radius: 5px;
    margin: 0;

    &:not(:first-of-type) {
      margin-top: 5px;
    }

    > h3 {
      padding: 0;
      margin: 0;
      line-height: 1.1;
      padding-bottom: 5px;
      border-bottom: solid 1px #ccc;
    }

    > div {
      display: flex;
      flex-flow: row nowrap;
      align-items: center;
      padding-top: 8px;
      padding-bottom: 5px;

      > b {
        width: 33.3333%;
        line-height: 1.2;
        display: inline-block;
        font-weight: bold;
        white-space: nowrap;
        overflow: hidden;

        > span {
          font-weight: bold;
          padding-left: 5px;
          text-align: right;
        }
      }
    }
  }
</style>
